<template>
  <div id="test-id">
    <van-button type="primary" @click="addAreaWater">区域水印</van-button>
    <van-button type="primary" @click="change">DOM变化</van-button>
    <van-button type="primary" @click="changeDemo">DOM变化</van-button>

    <van-button type="default" @click="clear">清空</van-button>
    <div id="demo">
      <span v-if="dateText">{{ dateText }}</span>
      <img src="@/images/noImage.png" />
    </div>

    <van-uploader
      v-model="fileList"
      :after-read="afterRead"
      accept="image/*"
      show-upload
      multiple
      max-count="5"
    />
    <img v-show="myImg" :src="myImg" alt="" />
  </div>
</template>

<script lang="ts" setup>
import { Uploader as VanUploader, UploaderFileListItem } from 'vant'
import { ref } from 'vue'
import { fileInfo } from '@/model/WaterModel/WaterModel'
import { detailImg, domWatermark } from '@/utils/water-mark/image-mark'
import waterMark from '@/utils/water-mark/dom-watermark'
import { fileToBase64 } from '@/utils/file'

const myImg = ref('')
const dateText = ref(new Date().toString())
let mark: waterMark
const fileList = ref<UploaderFileListItem[]>([])

const initList = (list: fileInfo[]) => {
  list.forEach((f, i) => {
    if (!f.file) return
    fileToBase64(f.file, (base64) => {
      fileList.value[i].file = f.file
      fileList.value[i].content = base64 as string
    })
  })
  myImg.value = fileList.value[fileList.value.length - 1].content as string
}

const changeDemo = () => {
  initList(fileList.value)
}

const afterRead = (files: NonNullable<UploaderFileListItem | UploaderFileListItem[]>): void => {
  const fileArr = Array.isArray(files) ? files : [files]
  Promise.all(fileArr.map((f) => detailImg(f.file as File))).then((res) => {
    const fileNewList = fileArr.map((vanFile, i) => ({
      fileName: vanFile.file && vanFile.file.name,
      file: res[i] as File,
      content: '',
      fileType: vanFile.file && vanFile.file.type
    }))
    initList(fileNewList)
  })
}

const addAreaWater = () => {
  if (mark) {
    mark.remove()
    mark.drawCanvas()
  } else {
    mark = domWatermark({ id: 'demo' })
  }
}
const change = () => {
  dateText.value = dateText.value ? '' : new Date().toString()
}
const clear = () => {
  mark.remove()
}
// const changeFileList = () => {
//   fileList.forEach((_, i) => {
//     fileList[i].file = fileNewList[i].file
//     fileList[i].content = fileNewList[i].content
//   })
// }
</script>

<style lang="less" scoped>
#test-id,
#demo {
  > img {
    width: 100%;
    // aspect-ratio: 2/1;
  }
}
</style>
